﻿using System.Configuration;
using System.IO;
using ErrorDumper.Configuration;

namespace ErrorDumper {
    public class DefaultExceptionDataSource : IExceptionDataSource {

        public const string DefaultEventLogSource = ".NET Runtime";

        public string VirtualPath { get; protected set; }
        public string PhysicalPath { get; protected set; }
        public string ConnectionStringName { get; protected set; }
        public string ConnectionString { get; protected set; }
        public string EventLogSource { get; protected set; }

        public DefaultExceptionDataSource() {
            EventLogSource = DefaultEventLogSource;

            // ReSharper disable DoNotCallOverridableMethodsInConstructor
            Initialize();
            // ReSharper restore DoNotCallOverridableMethodsInConstructor
        }

        protected virtual void Initialize() {
            LoadConfiguration();

            if (!string.IsNullOrWhiteSpace(VirtualPath) &&
                Path.IsPathRooted(VirtualPath))
                PhysicalPath = VirtualPath;

            if (!string.IsNullOrWhiteSpace(ConnectionStringName)) {
                var connStr = ConfigurationManager.ConnectionStrings[ConnectionStringName];
                if (connStr != null && !string.IsNullOrWhiteSpace(connStr.ConnectionString))
                    ConnectionString = connStr.ConnectionString;
            }
        }

        private static string TrimOrNull(string value) {
            return string.IsNullOrWhiteSpace(value) ? null : value.Trim();
        }

        protected virtual void LoadConfiguration() {
            var section = DataSourceConfigurationSection.GetSection();

            if (section == null)
                return;

            VirtualPath = TrimOrNull(section.VirtualPath);
            ConnectionStringName = TrimOrNull(section.ConnectionStringName);
            EventLogSource = TrimOrNull(section.EventLogSource) ?? DefaultEventLogSource;
        }
    }
}
